<?php
require_once 'init_app.php';

set_time_limit(0);

// пока только одежда и обувь
$categories = ORM::factory('category')
                ->where('is_bigcat', '=', 0)
                ->where('id', '>=', 1776)
                ->where('id', '<', 2189)
                ->find_all();
                
foreach ($categories as $category) {
    /*$brands = ORM::factory('brand')->get_brands($category, false, true);
    foreach ($brands as $brand) {
        
        $brand_id = $brand['id'];
        $count = $brand['count'];
        
        set_brand_denormalized_value($category->id, $brand_id, $count); 
    }  
    
    $shops = ORM::factory('shop')->get_shops($category, false, true);
    foreach ($shops as $shop) {
        
        $shop_id = $shop['id'];
        $count = $shop['count'];
        
        set_shop_denormalized_value($category->id, $shop_id, $count); 
    }  */
    
    $_categories = ORM::factory('category')->get_categories($category, false, false, true);
    foreach ($_categories as $_category) {
        
        $_category_id = $_category['id'];
        $count = $_category['count'];
        
        set_category_denormalized_value($category->id, $_category_id, $count); 
    }
}
                     
function set_brand_denormalized_value($category_id, $brand_id, $count) {
    try {
        DB::insert('catalog_brand_filters', array('category_id', 'brand_id', 'count'))
            ->values(array($category_id, $brand_id, $count))->execute();    
    } catch (Database_Exception $e) {
        DB::update('catalog_brand_filters')
            ->set(array('count' => $count))
            ->where('category_id', '=', $category_id) 
            ->where('brand_id', '=', $brand_id) 
            ->execute();
    }    
}

function set_shop_denormalized_value($category_id, $shop_id, $count) {
    try {
        DB::insert('catalog_shop_filters', array('category_id', 'shop_id', 'count'))
            ->values(array($category_id, $shop_id, $count))->execute();    
    } catch (Database_Exception $e) {
        DB::update('catalog_shop_filters')
            ->set(array('count' => $count))
            ->where('category_id', '=', $category_id) 
            ->where('shop_id', '=', $shop_id) 
            ->execute();
    }   
} 

function set_category_denormalized_value($category_id, $category_id2, $count) {
    try {
        DB::insert('catalog_category_filters', array('category_id', 'category_id2', 'count'))
            ->values(array($category_id, $category_id2, $count))->execute();    
    } catch (Database_Exception $e) {
        DB::update('catalog_category_filters')
            ->set(array('count' => $count))
            ->where('category_id', '=', $category_id) 
            ->where('category_id2', '=', $category_id2) 
            ->execute();
    }   
} 

echo 'ok';







